<?php
/**
 * ID生成器
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/25
 * Time: 14:08
 */
namespace app\service;


class IDBuilder {

    /**
     * 通过用户主键获取分库ID
     * @param $userID
     * @return int
     */
    static public function getMamiDBShardID($userID)
    {
        $checksum = crc32(md5(strtolower($userID)));
        if (8 == PHP_INT_SIZE) {
            if ($checksum > 2147483647) {
                $checksum = $checksum & (2147483647);
                $checksum = ~($checksum - 1);
                $checksum = $checksum & 2147483647;
            }
        }
        $hash = (abs($checksum) % 6);
        if ($hash < 10)
            $hash = '0' . $hash;

        return $hash;
    }

    /**
     * 用户ID生成器
     * @return string
     */
    static public function buildUserID()
    {
        $yCode = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
        $orderSn = $yCode[rand(0, 9)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(10, 99)) . uniqid();
        return $orderSn;
    }

    /**
     * 订单ID生成器
     * @param $orderTag 订单标识
     * @return string
     */
    static public function buildOrderID($orderTag=null)
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99)) . substr(md5(uniqid()),0,14);
        if(!is_null($orderTag)){
            $orderSn .= $orderTag . "-" . $orderSn;
        }
        return $orderSn;
    }

    /**
     * 生成唯一ID
     * @return string
     */
    static public function uniqueID()
    {
        static $guid = '';
        $uid = uniqid("", true);
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5(time())));
        $guid = substr($hash,  0,  8) . substr($hash,  8,  4) . substr($hash, 12,  4) . substr($hash, 16,  4) . substr($hash, 20, 12) ;
        return strtolower($guid);
    }


}